﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using SZHL.Data;
using Senparc.Weixin.QY.Entities;
namespace SZHL.UI.AppCode
{

    #region 业务模块
    public class ZH_CCXJB : BaseEFDao<ZH_CCXJ>
    {
    }


    public class ZH_GZRZB : BaseEFDao<ZH_GZRZ>
    {
        /// <summary>
        /// 获取工作日志列表
        /// </summary>
        /// <param name="type">工作日志类型</param>
        /// <param name="CRUser">创建人</param>
        /// <param name="searchFilter">查询条件</param>
        /// <param name="branchName">部门</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public DataTable GETGZRZList(string type, string CRUser, string searchFilter, string branchName, int page, ref int recordCount)
        {

            string strWhere = " ";

            if (CRUser != "")
            {
                strWhere += string.Format("   CRUser in('{0}')", CRUser);
            }
            if (branchName != "")
            {
                strWhere += string.Format("   BranchName='{0}'", branchName);
            }
            if (type != "")
            {
                strWhere += string.Format(" And  LeiBie='{0}'", type);
            }
            if (searchFilter != "")
            {
                strWhere += "And ( ";
                if (CRUser == "") //如果是我的日报菜单查询条件中不包含用户名
                {
                    strWhere += string.Format("  CRUserName like '%{0}%' or ", searchFilter);
                }
                strWhere += string.Format("  RBContent like '%{0}%')", searchFilter);
            }
            DataTable dt = new ZH_GZRZB().GetDataPager("ZH_GZRZ", "BranchName,RBContent,RBJSR,RBWCQK,RBDate,LeiBie,CRUser,CRDate,ID,Files,CRUserName  ", 8, page, "CRDate desc", strWhere, ref recordCount);
            string Ids = "";
            string fileIDs = "";
            foreach (DataRow row in dt.Rows)
            {
                Ids += row["ID"].ToString() + ",";
                if (!string.IsNullOrEmpty(row["Files"].ToString()))
                {
                    fileIDs += row["Files"].ToString() + ",";
                }
            }
            Ids = Ids.TrimEnd(',');
            fileIDs = fileIDs.TrimEnd(',');
            if (Ids != "")
            {
                DataTable dtPL = new JH_Auth_TLB().GetDTByCommand(string.Format("SELECT ID,MSGTLYID,MSGType,MSGContent,Points,CRDate,CRUser,CRUserName  FROM JH_Auth_TL WHERE MSGType='GZRZ' AND  MSGTLYID in ({0})", Ids));
                List<FT_File> FileList = new FT_FileB().GetEntities(d => fileIDs.Split(',').Contains(d.ID.ToString())).ToList();
                dt.Columns.Add("PLList", Type.GetType("System.Object"));
                dt.Columns.Add("FileList", Type.GetType("System.Object"));
                foreach (DataRow row in dt.Rows)
                {
                    row["PLList"] = dtPL.FilterTable("MSGTLYID=" + row["ID"]);
                    if (FileList.Count > 0)
                    {

                        string[] fileIds = row["Files"].ToString().Split(',');
                        row["FileList"] = FileList.Where(d => fileIds.Contains(d.ID.ToString()));
                    }
                }
            }

            return dt;
        }

        /// <summary>
        /// 获取所有日报列表
        /// </summary>
        /// <param name="type">日报类型</param>
        /// <param name="searchFilter">日报查询条件</param>
        /// <returns></returns>
        public DataTable GETALLGZRZList(string type, string searchFilter)
        {

            string strWhere = " ";
            if (type != "")
            {
                strWhere += string.Format(" And  LeiBie='{0}'", type);
            }
            if (searchFilter != "")
            {
                strWhere += "And ( ";

                strWhere += string.Format("  CRUserName like '%{0}%' or ", searchFilter);
                strWhere += string.Format("  RBContent like '%{0}%')", searchFilter);
            }
            string strSql = string.Format("select  BranchName,CONVERT(VARCHAR(10), RBDate,120) RBDate,LeiBie,CRUserName,RBContent,RBWCQK,ID  from ZH_GZRZ      where 1=1 " + strWhere + " order by CRDate desc");
            return new ZH_GZRZB().GetDTByCommand(strSql);
        }

    }
    public class ZH_KHGL_LXJLB : BaseEFDao<ZH_KHGL_LXJL>
    { }
    public class ZH_JFBXB : BaseEFDao<ZH_JFBX>
    {

        /// <summary>
        /// 获取编号
        /// </summary>
        /// <param name="tableName">表名称</param>
        public string GetFormCode(string tableName)
        {
            string strSql = string.Format("select top 1 formcode from {0} where CRDate>'{1}' order by CRDate DESC", tableName, DateTime.Now.ToShortDateString());
            object obj = new ZH_JFBXB().ExsSclarSql(strSql);
            string formCode = DateTime.Now.ToString("yyyyMMdd");
            if (obj == null || obj.ToString() == "")
            {
                formCode = formCode + "001";
            }
            else
            {
                string preFormCode = obj.ToString();
                int code = 0;
                int.TryParse(preFormCode.Substring(preFormCode.Length - 3), out code);
                formCode = formCode + (code + 1).ToString("000");
            }
            return formCode;
        }
    }

    public class ZH_LCSPB : BaseEFDao<ZH_LCSP>
    { }
    public class ZH_JFBX_ItemB : BaseEFDao<ZH_JFBX_Item>
    { }


    public class ZH_KHGLB : BaseEFDao<ZH_KHGL>
    {

    }

    public class ZH_HDBMB : BaseEFDao<ZH_HDBM>
    {

    }

    public class ZH_HDBM_ItemB : BaseEFDao<ZH_HDBM_Item>
    {

    }
    public class ZH_RCTXB : BaseEFDao<ZH_RCTX>
    {

    }
    public class ZH_RCTX_STATUSB : BaseEFDao<ZH_RCTX_STATUS>
    {

    }
    public class ZH_XMGLB : BaseEFDao<ZH_XMGL>
    {

    }

    public class ZH_GZJHB : BaseEFDao<ZH_GZJH>
    {

    }

    public class ZH_GZJH_ItemB : BaseEFDao<ZH_GZJH_Item>
    {

    }
    public class ZH_TXSXB : BaseEFDao<ZH_TXSX>
    {

    }
    public class JH_Auth_TLB : BaseEFDao<JH_Auth_TL>
    {
        public DataTable GetTL(string strMsgType, string MSGTLYID)
        {
            DataTable dtList = new DataTable();
            dtList = new ZH_RCTXB().GetDTByCommand("  SELECT ID,MSGTLYID,MSGType,MSGContent,CRDate,CRUser,CRUserName  FROM JH_Auth_TL WHERE MSGType='" + strMsgType + "' AND  MSGTLYID='" + MSGTLYID + "'");
            return dtList;
        }
    }
    public class JH_Auth_QYB : BaseEFDao<JH_Auth_QY>
    {

    }
    public class JH_Auth_User_CenterB : BaseEFDao<JH_Auth_User_Center>
    {
        /// <summary>
        /// 添加消息并发送微信消息
        /// </summary>
        /// <param name="UserInfo">用户信息</param>
        /// <param name="type">类型</param>
        /// <param name="title">标题</param>
        /// <param name="content">发送内容</param>
        /// <param name="Id">实体Id</param>
        /// <param name="JSR">接收人</param>
        public void SendMsg(JH_Auth_UserB.UserInfo UserInfo, string type, string title, string content, int Id, string JSR, int PIID = 0)
        {
            JH_Auth_User_Center userCenter = new JH_Auth_User_Center();
            userCenter.CRUser = UserInfo.User.UserName;
            userCenter.CRDate = DateTime.Now;
            userCenter.MsgContent = content;
            userCenter.MsgType = title;
            userCenter.UserFrom = UserInfo.User.UserName;
            userCenter.isRead = "N";
            userCenter.wxLink = WXHelp.GetWxLink(type, Id.ToString());
            userCenter.MsgLink = WXHelp.GetMsgLink(type, Id.ToString(), PIID);
            string sendUser = "";
            foreach (string people in JSR.Split(','))
            {
                if (!string.IsNullOrEmpty(people) && UserInfo.User.UserName != people)
                {
                    userCenter.UserTO = people;
                    new JH_Auth_User_CenterB().Insert(userCenter);
                    sendUser += people + ",";
                }

            }
            //发送消息
            Article ar = new Article();
            ar.Title = title;
            ar.Description = userCenter.MsgContent;
            if (!string.IsNullOrEmpty(sendUser))
            {
                WXHelp.SendTH(ar, type, Id, sendUser.TrimEnd(','));
            }
        }
    }



    public class ZH_DXGLB : BaseEFDao<ZH_DXGL>
    {

    }


    public class ZH_NOTEB : BaseEFDao<ZH_NOTE>
    { }

    public class ZH_TXLB : BaseEFDao<ZH_TXL>
    { }

    public class ZH_CQQDB : BaseEFDao<ZH_CQQD>
    { }

    public class JH_Auth_KQB : BaseEFDao<JH_Auth_KQ>
    { }
    public class ZH_ZXZXB : BaseEFDao<ZH_ZXZX>
    { }
    public class ZH_ZXZX_ItemB : BaseEFDao<ZH_ZXZX_Item>
    { }
    public class ZH_JSTXB : BaseEFDao<ZH_JSTX>
    { }
    public class ZH_JSTX_ItemB : BaseEFDao<ZH_JSTX_Item>
    { }
    public class ZH_JHAPB : BaseEFDao<ZH_JHAP>
    {

        /// <summary>
        /// 获取工作日志列表
        /// </summary>
        /// <param name="type">工作日志类型</param>
        /// <param name="CRUser">创建人</param>
        /// <param name="searchFilter">查询条件</param>
        /// <param name="branchName">部门</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public DataTable GETJHAPList(string type, string CRUser, string searchFilter, string branchName, int page, ref int recordCount)
        {

            string strWhere = " ";

            if (CRUser != "")
            {
                strWhere += string.Format("   CRUser in('{0}')", CRUser);
            }
            if (branchName != "")
            {
                strWhere += string.Format("   BranchName='{0}'", branchName);
            }
            if (type != "")
            {
                strWhere += string.Format(" And  LeiBie='{0}'", type);
            }
            if (searchFilter != "")
            {
                strWhere += "And ( ";
                if (CRUser == "") //如果是我的日报菜单查询条件中不包含用户名
                {
                    strWhere += string.Format("  CRUserName like '%{0}%' or ", searchFilter);
                }
                strWhere += string.Format("  RBContent like '%{0}%')", searchFilter);
            }
            DataTable dt = new ZH_JHAPB().GetDataPager("ZH_JHAP", "BranchName,RBContent,RBJSR,RBWCQK,RBDate,LeiBie,CRUser,CRDate,ID,Files,CRUserName  ", 8, page, "CRDate desc", strWhere, ref recordCount);
            string Ids = "";
            string fileIDs = "";
            foreach (DataRow row in dt.Rows)
            {
                Ids += row["ID"].ToString() + ",";
                if (!string.IsNullOrEmpty(row["Files"].ToString()))
                {
                    fileIDs += row["Files"].ToString() + ",";
                }
            }
            Ids = Ids.TrimEnd(',');
            fileIDs = fileIDs.TrimEnd(',');
            if (Ids != "")
            {
                DataTable dtPL = new JH_Auth_TLB().GetDTByCommand(string.Format("SELECT ID,MSGTLYID,MSGType,MSGContent,Points,CRDate,CRUser,CRUserName  FROM JH_Auth_TL WHERE MSGType='JHAP' AND  MSGTLYID in ({0})", Ids));
                List<FT_File> FileList = new FT_FileB().GetEntities(d => fileIDs.Split(',').Contains(d.ID.ToString())).ToList();
                dt.Columns.Add("PLList", Type.GetType("System.Object"));
                dt.Columns.Add("FileList", Type.GetType("System.Object"));
                foreach (DataRow row in dt.Rows)
                {
                    row["PLList"] = dtPL.FilterTable("MSGTLYID=" + row["ID"]);
                    if (FileList.Count > 0)
                    {

                        string[] fileIds = row["Files"].ToString().Split(',');
                        row["FileList"] = FileList.Where(d => fileIds.Contains(d.ID.ToString()));
                    }
                }
            }

            return dt;
        }

        /// <summary>
        /// 获取所有日报列表
        /// </summary>
        /// <param name="type">日报类型</param>
        /// <param name="searchFilter">日报查询条件</param>
        /// <returns></returns>
        public DataTable GETALLJHAPList(string type, string searchFilter)
        {

            string strWhere = " ";
            if (type != "")
            {
                strWhere += string.Format(" And  LeiBie='{0}'", type);
            }
            if (searchFilter != "")
            {
                strWhere += "And ( ";

                strWhere += string.Format("  CRUserName like '%{0}%' or ", searchFilter);
                strWhere += string.Format("  RBContent like '%{0}%')", searchFilter);
            }
            string strSql = string.Format("select  BranchName,CONVERT(VARCHAR(10), RBDate,120) RBDate,LeiBie,CRUserName,RBContent,RBWCQK,ID  from ZH_JHAP      where 1=1 " + strWhere + " order by CRDate desc");
            return new ZH_JHAPB().GetDTByCommand(strSql);
        }
    }
    #endregion



    #region 扩展模块
    public class KZ_HTGLB : BaseEFDao<KZ_HTGL>
    {

    }
    public class KZ_HTGL_ZFJLB : BaseEFDao<KZ_HTGL_ZFJL>
    {

    }
    public class KZ_KJGLB : BaseEFDao<KZ_KJGL>
    {

    }
    public class KZ_XMGLB : BaseEFDao<KZ_XMGL>
    {

    }

    public class KZ_UserInfoB : BaseEFDao<KZ_UserInfo>
    {

    }
    public class KZ_LSGLB : BaseEFDao<KZ_LSGL>
    {

    }
    public class KZ_GYSGLB : BaseEFDao<KZ_GYSGL>
    {

    }
    #endregion


    #region 文档管理模块
    public class FT_FolderB : BaseEFDao<FT_Folder>
    {


        public FoldFile GetWDTREE(int FolderID, ref List<FoldFileItem> ListID, string strUserName = "")
        {
            List<FT_Folder> ListAll = new FT_FolderB().GetEntities().ToList();
            FT_Folder Folder = new FT_FolderB().GetEntity(d => d.ID == FolderID);
            FT_FolderB.FoldFile Model = new FT_FolderB.FoldFile();
            Model.Name = Folder.Name;
            Model.FolderID = Folder.ID;
            Model.CRUser = Folder.CRUser;
            Model.PFolderID = Folder.PFolderID.Value;
            ListID.Add(new FoldFileItem() { ID = Folder.ID, Type = "folder" });
            if (strUserName != "")
            {
                Model.SubFileS = new FT_FileB().GetEntities(d => d.FolderID == Folder.ID && d.CRUser == strUserName).ToList();
            }
            else
            {
                Model.SubFileS = new FT_FileB().GetEntities(d => d.FolderID == Folder.ID).ToList();
            }
            foreach (var item in Model.SubFileS)
            {
                ListID.Add(new FoldFileItem() { ID = item.ID, Type = "file" });

            }
            Model.SubFolder = new FT_FolderB().GETNEXTFLODER(Folder.ID, ListAll, ref ListID, strUserName);
            return Model;
        }


        private List<FoldFile> GETNEXTFLODER(int FolderID, List<FT_Folder> ListAll, ref List<FoldFileItem> ListID, string strUserName = "")
        {
            List<FoldFile> ListData = new List<FoldFile>();
            var list = ListAll.Where(d => d.PFolderID == FolderID);
            if (strUserName!="")
            {
                list = list.Where(d => d.CRUser == strUserName);
            }
            foreach (var item in list)
            {
                FoldFile FolderNew = new FoldFile();
                FolderNew.FolderID = item.ID;
                FolderNew.Name = item.Name;
                FolderNew.CRUser = item.CRUser;
                FolderNew.PFolderID = item.PFolderID.Value;
                if (strUserName != "")
                {
                    FolderNew.SubFileS = new FT_FileB().GetEntities(d => d.FolderID == item.ID && d.CRUser == strUserName).ToList();
                }
                else
                {
                    FolderNew.SubFileS = new FT_FileB().GetEntities(d => d.FolderID == item.ID).ToList();
                }
                foreach (var SubFile in FolderNew.SubFileS)
                {
                    ListID.Add(new FoldFileItem() { ID = SubFile.ID, Type = "file" });
                }
                FolderNew.SubFolder = GETNEXTFLODER(item.ID, ListAll, ref ListID, strUserName);
                ListData.Add(FolderNew);
                ListID.Add(new FoldFileItem() { ID = item.ID, Type = "folder" });
            }
            return ListData;

        }


        /// <summary>
        /// 复制树状结构
        /// </summary>
        /// <param name="FloderID"></param>
        /// <param name="PID"></param>
        public void CopyFloderTree(int FloderID, int PID)
        {
            List<FoldFileItem> ListID = new List<FoldFileItem>();
            FoldFile Model = new FT_FolderB().GetWDTREE(FloderID, ref ListID);
            FT_Folder Folder = new FT_FolderB().GetEntity(d => d.ID == Model.FolderID);
            Folder.PFolderID = PID;
            new FT_FolderB().Insert(Folder);

            //更新文件夹路径Code
            FT_Folder PFolder = new FT_FolderB().GetEntity(d => d.ID == PID);
            Folder.Remark = PFolder.Remark + "-" + Folder.ID;
            new FT_FolderB().Update(Folder);

            foreach (FT_File file in Model.SubFileS)
            {
                file.FolderID = Folder.ID;
                new FT_FileB().Insert(file);
            }
            GreateWDTree(Model.SubFolder, Folder.ID);
        }

        /// <summary>
        /// 根据父ID创建树装结构文档
        /// </summary>
        /// <param name="ListFoldFile"></param>
        private void GreateWDTree(List<FoldFile> ListFoldFile, int newfolderid)
        {

            foreach (FoldFile item in ListFoldFile)
            {

                FT_Folder PModel = new FT_FolderB().GetEntity(d => d.ID == item.FolderID);
                PModel.PFolderID = newfolderid;
                new FT_FolderB().Insert(PModel);

                //更新文件夹路径Code
                FT_Folder PFolder = new FT_FolderB().GetEntity(d => d.ID == newfolderid);
                PModel.Remark = PFolder.Remark + "-" + PModel.ID;
                new FT_FolderB().Update(PModel);

                foreach (FT_File file in item.SubFileS)
                {
                    file.FolderID = PModel.ID;
                    new FT_FileB().Insert(file);
                }

                GreateWDTree(item.SubFolder, PModel.ID);



            }
        }



        /// <summary>
        /// 判断用户是否有当前文件件的管理权限
        /// </summary>
        /// <param name="FloderID"></param>
        /// <param name="strUserName"></param>
        /// <returns></returns>
        public string isHasManage(string FloderID,string strUserName)
        {
            string strReturn = "N";
            FT_Folder Model = new FT_FolderB().GetEntities(d => d.ID.ToString() == FloderID).SingleOrDefault();
            if (!string.IsNullOrEmpty(Model.Remark))
            {
                string str = Model.Remark.ToFormatLike();
                DataTable dt = new FT_FolderB().GetDTByCommand("SELECT * FROM FT_Folder WHERE ','+UploadaAuthUsers+','  like '%," + strUserName + ",%'  AND ID IN ('" + Model.Remark.ToFormatLike('-') + "')");
                if (dt.Rows.Count>0)
                {
                    strReturn = "Y";
                }
            }
            return strReturn;
        }


        public void DelWDTree(int FolderID)
        {
            List<FoldFileItem> ListID = new List<FoldFileItem>();
            new FT_FolderB().GetWDTREE(FolderID, ref ListID);
            foreach (FoldFileItem listitem in ListID)
            {
                if (listitem.Type == "file")
                {
                    new FT_FileB().Delete(d => d.ID == listitem.ID);
                }
                else
                {
                    new FT_FolderB().Delete(d => d.ID == listitem.ID);
                }
            }

        }



        public class FoldFile
        {
            public int FolderID { get; set; }
            public string Name { get; set; }
            public string CRUser { get; set; }
            public int PFolderID { get; set; }
            public string Remark { get; set; }

            public List<FoldFile> SubFolder { get; set; }
            public List<FT_File> SubFileS { get; set; }

        }
        public class FoldFileItem
        {
            public int ID { get; set; }
            public string Type { get; set; }

        }
    }
    public class FT_FileB : BaseEFDao<FT_File>
    {
        public void AddVersion(FT_File oldmodel, string strMD5, string strSIZE)
        {
            FT_File_Vesion Vseion = new FT_File_Vesion();
            Vseion.FileMD5 = oldmodel.FileMD5;
            Vseion.RFileID = oldmodel.ID;
            new FT_File_VesionB().Insert(Vseion);
            //添加新版本

            oldmodel.FileVersin = oldmodel.FileVersin + 1;
            oldmodel.FileMD5 = strMD5;
            oldmodel.FileSize = strSIZE;
            new FT_FileB().Update(oldmodel);
            //修改原版本

        }



        /// <summary>
        /// 判断同一目录下是否有相同文件(不判断应用文件夹)
        /// </summary>
        /// <param name="strMD5"></param>
        /// <param name="strFileName"></param>
        /// <param name="FolderID"></param>
        /// <returns></returns>
        public FT_File GetSameFile(string strFileName, int FolderID)
        {
            return new FT_FileB().GetEntities(d => d.FolderID == FolderID && (d.Name + "." + d.FileExtendName) == strFileName && d.FolderID != 3).FirstOrDefault();
        }


        /// <summary>
        /// 获取文件在服务器上的预览文件路径
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string GetYLURL(FT_File model)
        {
            string YLURL = "";
            if (new List<string>() { "doc", "docx", "ppt", "pptx" }.Contains(model.FileExtendName.ToLower()))//OFFICE格式
            {
                YLURL = "/View/Common/VIEWPDF.aspx?path=/Upload/" + model.CRDate.Value.ToString("yyyyMM") + "/PDF/" + model.FileMD5 + ".pdf";
            }
            if (new List<string>() { "pdf", "txt", "html" }.Contains(model.FileExtendName.ToLower()))//普通格式
            {
                YLURL = "/View/Common/VIEWPDF.aspx?path=/Upload/" + model.CRDate.Value.ToString("yyyyMM") + "/" + model.FileMD5 + "." + model.FileExtendName;
            }
            if (new List<string>() { "jpg", "jpeg", "gif", "png" }.Contains(model.FileExtendName.ToLower()))//图片格式
            {
                YLURL = "/View/Common/ImageView.html?path=/Upload/" + model.CRDate.Value.ToString("yyyyMM") + "/" + model.FileMD5 + "." + model.FileExtendName;
            }
            if (new List<string>() { "flv", "f4v", "mp4", "webm", "ogg", "m3u8" }.Contains(model.FileExtendName.ToLower()))//视频格式
            {
                YLURL = "/View/Common/VideoView.html?path=/Upload/" + model.CRDate.Value.ToString("yyyyMM") + "/" + model.FileMD5 + "." + model.FileExtendName;
            }
            return YLURL;
        }

    }

    public class FT_File_CollectB : BaseEFDao<FT_File_Collect>
    {

    }

    public class FT_File_DownhistoryB : BaseEFDao<FT_File_Downhistory>
    {

    }


    public class FT_File_ShareB : BaseEFDao<FT_File_Share>
    {

    }


    public class FT_File_UserAuthB : BaseEFDao<FT_File_UserAuth>
    {

    }


    public class FT_File_UserTagB : BaseEFDao<FT_File_UserTag>
    {

    }

    public class FT_File_VesionB : BaseEFDao<FT_File_Vesion>
    {

    }

    #endregion
    #region 企捷云网站验证码
    public class QJY_IdentityB : BaseEFDao<QJY_Identity>
    { }
    #endregion

}